/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mahumLogs.filters;

import com.mahumLogs.beans.SessionBean;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
@WebFilter(filterName = "LoginFilter", urlPatterns = {"*.jsf"})
public class LoginFilter implements Filter {
    
    private @Inject SessionBean session;
     
    public LoginFilter() {
    }
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // check whether session variable is set
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            String url = req.getRequestURI();
            String contextPath = req.getContextPath();
            
            //  allow user to proccede if url is login.xhtml or user logged in or user is accessing any page in //public folder
            String reqURI = req.getRequestURI();
            if (session.isIsLogged()) {
                if(url.equals(contextPath + "/")){
                    if(session.getAdmin() != null){
                        res.sendRedirect(contextPath + "/admin/index.jsf");
                    } else {
                        res.sendRedirect(contextPath + "/user/gererMachines.jsf");
                    }
                    
                } else {
                    session.setLastUrlVisited(url);
                    chain.doFilter(request, response);
                }
            } else {
                if(url.startsWith(contextPath + "/javax.faces.resource/") 
                        || url.startsWith(contextPath + "/resources/")
                        || url.startsWith(contextPath + "/login.jsf")
                        || url.equals(contextPath + "/")){
                    chain.doFilter(request, response);
                } else {
                    res.sendRedirect(contextPath + "/");
                }
            }
        } catch (Throwable t) {
            System.out.println(t.getMessage());
        }
    } //doFilter
 
    @Override
    public void destroy() {
         
    }
}